//
//  UserAccountMode.swift
//  微博001
//
//  Created by apple on 15/12/14.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountMode: NSObject {
    
    //定义用户模型对象的属性
    var userAccount: UserAccount?

    override init() {
        
        //对象的构造 分 两步
        //先构造本来  再构造父类
        //        self.name = name
        userAccount = UserAccount.loadAccount()
        super.init()
    }
    
    var token: String? {
        return userAccount?.access_token
    }
    
    //用户名
    var userName: String? {
        return userAccount?.name
    }
    
    //用户头像的URl
    var headURL: NSURL? {
        let url = NSURL(string: userAccount?.avatar_large ?? "")
        return url
    }
    
    //计算性属性 用户是否登陆
    var userLogin: Bool {
        return userAccount?.access_token != nil
    }

    func loadAccessToken(code: String,finished: (isSuccess: Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type ":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        NetworkTools.sharedTools.requestJSONDict(.POST,urlString:urlString, parameters: parameters) { (dict, error) -> () in
            if error != nil {
                //执行失败的回掉
                finished(isSuccess: false)
                return
            }
            
                
            let userAccout = UserAccount(dict: dict!)
            self.loadUserInfo(userAccout, finished: finished)

            print(dict)
        }
    }
    
    // MARK: 获取用户信息
    private func loadUserInfo(account: UserAccount ,finished: (isSuccess: Bool) -> ()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        if let token = account.access_token ,userID = account.uid {
            
            let parameters = ["access_token":token,"uid":userID]
            
            NetworkTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters, finished: { (dict, error) -> () in
                
                if error != nil {
                    print(error)
                    finished(isSuccess: false)
                    return
                }


                //获取用户信息
                let avatar_large = dict!["avatar_large"] as! String
                let name = dict!["name"] as! String
                //给account 对象的属性做赋值操作
                account.name = name
                account.avatar_large = avatar_large
                //获取用户信息的完整自定义对象
                //存储自定义对象
                account.saveAccount()
                //执行成功的回调
                finished(isSuccess: true)
            })
        }
    }
}
